package com.jlz.actions.weibo;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Standard;
import org.springframework.beans.factory.annotation.Autowired;

import com.jlz.weibo.FileUtils;
import com.julewa.loading.ClientImpl;

import weibo4j.Status;
import weibo4j.Weibo;
import weibo4j.WeiboException;
import weibo4j.http.*;

@Standard(rest="oauth_verifier")
public class IndexAction {
	@Autowired ClientImpl ClientImpl;
	private String oauth_verifier;
//	private String info;
	private String pic;
	private static String preffix = "../../../../../../pics/";
	
	private static String callBack = "http://localhost:8080/Zoo/weibo/publishPic";
	static{		
		System.setProperty("weibo4j.oauth.consumerKey", "2422782496");  
		System.setProperty("weibo4j.oauth.consumerSecret","8ccfe84a7270088ef3420fb3013c0737");
	}
	
	//认证
	public String execute(){
		return "pubweibo";
	}
	
	
	@Action("publishPic")
	public String publishWB(){
		AccessToken accessToken = null;
		RequestToken requestToken=(RequestToken) ClientImpl.getRequest().getSession().getAttribute("requestToken");
		if (requestToken == null) {
			oauth();
		}
		if(oauth_verifier!=null && !oauth_verifier.equals("")){
			Weibo weibo = new Weibo();
			try {
				accessToken = (AccessToken) ClientImpl.getRequest().getSession().getAttribute("accessToken");
				if (accessToken == null) {
					accessToken = weibo.getOAuthAccessToken(requestToken.getToken(), requestToken.getTokenSecret(), oauth_verifier);
				}
			} catch (WeiboException e) {
				e.printStackTrace();
				System.out.println("用户没有赋权限或者出现异常");
				return "pubweibo";
			}
			weibo.setToken(accessToken.getToken(), accessToken.getTokenSecret());
			String filePath = generateFilePath(pic);
			String des = getDesByFilePath(filePath);
			try {
				byte[] content = readFileImage(filePath);
				ImageItem pic = new ImageItem("pic", content);
	
				Status status = weibo.uploadStatus(URLEncoder.encode(des, "UTF-8"), pic);
				ClientImpl.getRequest().getSession().setAttribute("accessToken",accessToken);
				status.toString();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		
		return "pubweibo";
	}	

	private String getDesByFilePath(String filePath){
		String des = "";
		Map<String,String> desMap = new HashMap<String,String>();
		
		filePath = filePath.substring(filePath.lastIndexOf("/")+1);
		filePath = filePath.substring(0,filePath.indexOf(FileUtils.configMap.get("suffix")));
		
		//这里的filaPath是文件名称，desPathMap中key是文件名，value是一个map，这个map中存有des
		//并且还有des中需要替换的字符串
		desMap = FileUtils.picDesMap.get(filePath);

		des = doReplaceStr(desMap);
		
		return des;
	}
	
	//看看我在雨燕改装的 ${car}  吧, 帅不? 你也想要来一辆? 那就来参加${title}吧, 地址是${url}
	private String doReplaceStr(Map<String,String> desMap){
		//需要转义，因为$和{}都是特殊字符
		String des = desMap.get(FileUtils.msg);
		String title = desMap.get(FileUtils.title);
		String car = desMap.get(FileUtils.car);
		String url = desMap.get(FileUtils.url);
		
		des = des.replaceAll(Pattern.quote(FileUtils.configMap.get("car")), car)
				 .replaceAll(Pattern.quote(FileUtils.configMap.get("title")), title)
				 .replaceAll(Pattern.quote(FileUtils.configMap.get("url")), url);
		return des;
	}
	
	@Action("cancel")
	public String toCancel(){
		return "pubweibo";
	}
	
	private String oauth(){
		RequestToken requestToken = null;
		Weibo weibo = new Weibo();
		try {
			requestToken = weibo.getOAuthRequestToken(callBack);
			if(requestToken == null){
				ClientImpl.putError("认证失败，请检查!");
			}
			ClientImpl.getRequest().getSession().setAttribute("requestToken", requestToken);
			ClientImpl.getResponse().sendRedirect(requestToken.getAuthorizationURL());
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return "pubweibo";
	}
	

	private byte[] readFileImage(String filename) throws IOException {
		File picFile = new File(filename);
		BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(picFile));
		int len = bufferedInputStream.available();
		byte[] bytes = new byte[len];
		int r = bufferedInputStream.read(bytes);
		if (len != r) {
			bytes = null;
			throw new IOException("读取文件不正确");
		}
		bufferedInputStream.close();
		return bytes;
	}
	
	private String generateFilePath(String name){
		StringBuilder filePath = new StringBuilder();
		filePath.append(IndexAction.class.getResource("").getPath().substring(1));
		filePath.append(preffix);
		if (name == null) {
			filePath.append("0");
		}else {
			char[] wordsCharArr = name.toCharArray();
			if (wordsCharArr == null || wordsCharArr.length<1) {
				filePath.append("0");
			}else {
				int sum = 0;
				for (int i = 0; i < wordsCharArr.length; i++) {
					sum += (int)wordsCharArr[i];
				}
				int mod = Integer.valueOf(FileUtils.configMap.get("mod"));
				sum = sum%mod;
				filePath.append(sum);
			}
		}
		
		filePath.append(FileUtils.configMap.get("suffix"));
		return filePath.toString();
	}
//	
//	@Action("publishpic")
//	public String pubPicEntrance(){
//		oauth_verifier = ClientImpl.getRequest().getParameter("oauth_verifier");
//		this.setOauth_verifier(oauth_verifier);
//		return "pubpic";
//	}
//	
//	
//	@Action("publicImage")
//	public String publicImage() {
//		try {
//			Weibo weibo = new Weibo();
//			RequestToken requestToken=(RequestToken) ClientImpl.getRequest().getSession().getAttribute("requestToken");
//			if (requestToken == null) {
//				return "call";
//			}
//
//			AccessToken accessToken = (AccessToken) ClientImpl.getRequest().getSession().getAttribute("accessToken");
//			if (accessToken == null) {
//				accessToken = weibo.getOAuthAccessToken(requestToken.getToken(), requestToken.getTokenSecret(), oauth_verifier);
//				return "call";
//			}
//			weibo.setToken(accessToken.getToken(), accessToken.getTokenSecret());
//			String filePath = generateFilePath(pic);
//			
//			try {
//				byte[] content = readFileImage(filePath);
//				ImageItem pic = new ImageItem("pic", content);
//	
//				Status status = weibo.uploadStatus(URLEncoder.encode("神马图片", "UTF-8"), pic);
//				System.out.println("Successfully upload the status to [" + status.getText() + "].");
//			} catch (Exception e1) {
//				e1.printStackTrace();
//			}
//		} catch (Exception ioe) {
//			System.out.println("Failed to read the system input.");
//		}
//		return "pubpic";
//	}
//
//private void publishWeiBo(AccessToken access, String content) {
//	try {
//		Weibo weibo = new Weibo();
//		weibo.setToken(access.getToken(), access.getTokenSecret());
//        Status status = weibo.updateStatus(content);
//		System.out.println("Successfully updated the status to [" + status.getText() + "].");
//	} catch (WeiboException e) {
//		e.printStackTrace();
//	}
//}
	public String getOauth_verifier() {
		return oauth_verifier;
	}


	public void setOauth_verifier(String oauthVerifier) {
		oauth_verifier = oauthVerifier;
	}

//	public String getInfo() {
//		return info;
//	}
//
//	public void setInfo(String info) {
//		this.info = info;
//	}

	public String getPic() {
		return pic;
	}

	public void setPic(String pic) {
		this.pic = pic;
	}

}
